const app = getApp();
const config = require('../../../config.js');
const util = require('../../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isDefault: 0,
    jjr : "",
    sjh: "",
    dz: "",
    locationAddr : ""
  },
  bindPickerChange: function (e) {
    this.setData({
      areaIndex: e.detail.value
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // app.contactsLongitude = "";
    // app.contactsLatitude = "";
    app.contactsAddr = "";
    this.setData({ isDefault_c: "wu", isDefault_d: "sos" });
    let temptitle = "";
    if ("addSender" == options.title) {
      temptitle = "新建发货人";
    } else if ("editSender" == options.title) {
      temptitle = "编辑发货人";
    }
    wx.setNavigationBarTitle({ title: temptitle });
    if (null != options.sender && "" != options.sender){
      let sender = JSON.parse(options.sender);
      if (sender != null && sender != "") {
        if (sender.id != null && sender.id != "") {
          let locationAddrTemp = "";
          let contactAddressTemp = "";
          
          if (sender.contactAddress.indexOf('⊙') != -1) {
            locationAddrTemp = sender.contactAddress.split('⊙')[0];
            sender.locationAddr = locationAddrTemp;
            app.contactsAddr = locationAddrTemp;
            // app.locationAddr = locationAddrTemp;
            if (sender.contactAddress.split('⊙').length > 1) {
              contactAddressTemp = sender.contactAddress.split('⊙')[1];
              sender.contactAddress = contactAddressTemp;
            }
          } else {
            contactAddressTemp = sender.contactAddress;
          }
          this.data.id = sender.id;
          this.data.jjr = sender.contactName;
          this.data.sjh = sender.contactMobile;
          this.data.dz = contactAddressTemp;
          this.data.locationAddr = locationAddrTemp;
          this.data.isDefault = sender.isDefault;
        }
        // console.log(sender);
        if (sender.isDefault == 1) {
          this.setData({ user: sender, isDefault_c: "wu_h", isDefault_d: "sos_h" });
        } else if (sender.isDefault == 0) {
          this.setData({ user: sender, isDefault_c: "wu", isDefault_d: "sos" });
        }
      }
    }
  },
  /**
   * 获取发货人当前位置
   */
  getSenderLocation: function (e) {
    // wx.navigateTo({
    //   url: "/pages/user/contacts/position"
    // });
    var _this = this;
    wx.chooseLocation({
      success: function (res) {
        wx.hideLoading();
        // console.log(res);
        // app.contactsLongitude = res.longitude;
        // app.contactsLatitude = res.latitude;
        console.info(res.address);
        console.info(res.name);
        if (null != res.address && "" != res.address && null != res.name && "" != res.name) {
          if (res.address != res.name) {
            app.contactsAddr = res.address + res.name;
          } else {
            app.contactsAddr = res.address;
          }
          _this.data.locationAddr = app.contactsAddr;
          _this.setData({
            locationAddr: app.senderAddr,
            senderLongitude: res.longitude,
            senderLatitude: res.latitude
          });
        }

        // wx.navigateTo({
        //   url: "/pages/index/index?address=" + res.name
        // });
      },
      fail: function (err) {
        console.log(err)
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // console.log(app.contactsLongitude);
    // console.log(app.contactsLatitude);
    // console.log(app.contactsAddr);
    if (undefined != app.contactsAddr && "" != app.contactsAddr) {
      this.data.locationAddr = app.contactsAddr;
      this.setData({ locationAddr: app.contactsAddr});
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // },
  /**
   * 提交保存信息
   */
  save: function () {
    let vipMemberId = app.loginUser.id;
    // console.log(this.data);
    if (checkNull(this.data.jjr)) {
      app.tip('请填写发货人', 'none');
      return;
    } else {
      if (!app.inputZhengZe(this.data.jjr)) {
        app.tip("请删除发货人中的特殊符号", "none");
        return false;
      }
    }
    if (checkNull(this.data.sjh)) {
      app.tip('请填写手机号', 'none');
      return;
    }
    if (!util.checkMobile(this.data.sjh)) {
      app.tip('请填写正确手机号', 'none');
      return;
    }
    if (!checkNull(this.data.dz)){
      if (app.contactsAddr == undefined || app.contactsAddr == "") {
        app.tip('请选择地址', 'none');
        return;
      }
    }
    // if (checkNull(this.data.dz)) {
    //   app.tip('请填写地址', 'none')
    //   return;
    // }
    var menpaihao = "";
    if (this.data.dz != undefined && this.data.dz!= null){
      menpaihao = this.data.dz
    }
    wx.showLoading({ mask: true, title: "加载中" });
    let par = { "data": 
    '{"vipMemberId":"' + app.loginUser.id + 
      '","contactName":"' + this.data.jjr + 
      '","contactMobile":"' + this.data.sjh + 
      '","contactAddress":"' + ((this.data.locationAddr != undefined && this.data.locationAddr != '') ? this.data.locationAddr + '⊙' + menpaihao : '') + 
      '","isDefault":"' + this.data.isDefault +
      '","longitude":"' + (this.data.senderLongitude != undefined ? this.data.senderLongitude : '') +
      '","latitude":"' + (this.data.senderLatitude != undefined ? this.data.senderLatitude : '')
    +'"}'};
    // console.log(par);
    let url = config.requestUrl + "senderContactInfo/add";
    if(this.data.id != null && this.data.id != ""){
      par = { "data": 
      '{"vipMemberId":"' + app.loginUser.id + 
      '","contactName":"' + this.data.jjr + 
      '","contactMobile":"' + this.data.sjh + 
      '","contactAddress":"' + ((this.data.locationAddr != undefined && this.data.locationAddr != '')? this.data.locationAddr + '⊙' + menpaihao : '') + 
      '","isDefault":"' + this.data.isDefault +
      '","longitude":"' + (this.data.senderLongitude != undefined ? this.data.senderLongitude : '') +
      '","latitude":"' + (this.data.senderLatitude != undefined ? this.data.senderLatitude : '') + 
      '","id":"'+this.data.id+'"}' };
      url = config.requestUrl + "senderContactInfo/edit";
    }
    // console.log(url);
    wx.request({
      url: url,
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"//;charset=utf-8
      },
      data: par,
      success: function (msg) {
        // console.log(msg);
        wx.hideLoading();
        if (msg.data.code == 100){
          // wx.redirectTo({
          //   url: '../contacts/contacts?title=navigate&type=sender'
          // })
          wx.navigateBack({
            delta: 1
          })
        }else{
          app.tip(msg.data.msg == null ? "新建发货人失败" : msg.data.msg, 'none');
        }
      },
      fail: function (msg) {
        // console.log(msg);
        app.tip("新建发货人失败",'none');
        wx.hideLoading();
      }
    });
  },
  /**
   * 取消
   */
  goBack: function () {
    // wx.redirectTo({
    //   url: '../contacts/contacts?title=navigate&type=sender'
    // })
    wx.navigateBack({
      delta: 1
    })
  },
  /**
   * 默认设置
   */
  changeDefault: function (e) {
    // console.log(e.target.dataset.c);
    // console.log(e.target.dataset.d);
    if (e.target.dataset.c == "wu" || e.target.dataset.d == "sos") {
      this.setData({ isDefault_c: "wu_h", isDefault_d: "sos_h" });
      this.data.isDefault = 1;
    } else if (e.target.dataset.c == "wu_h" || e.target.dataset.d == "sos_h") {
      this.setData({ isDefault_c: "wu", isDefault_d: "sos" });
      this.data.isDefault = 0;
    }
  },
  /**
   * 发货人
   */
  jjr: function (e) {
    if (undefined != e.detail.value) {
      this.data.jjr = e.detail.value;
    } else {
      this.data.jjr = "";
    }

  },
  /**
   * 手机号
   */
  sjh: function (e) {
    if (undefined != e.detail.value) {
      this.data.sjh = e.detail.value;
    } else {
      this.data.sjh = "";
    }
    // console.log(this.data.sjh);
  },
  /**
   * 地址
   */
  dz: function (e) {
    if (undefined != e.detail.value) {
      this.data.dz = e.detail.value;
    } else {
      this.data.dz = "";
    }

  }
});
/**
 * 验证空
 */
function checkNull(str) {
  if (null == str || "" == str || undefined == str) {
    return true;
  } else {
    return false;
  }
}